package service

import (
	"errors"
	"go-proxy/domain/message"
	"go-proxy/initialize"
	"go-proxy/utils"

	"go.uber.org/zap"
)

var System = newSystemService()

type ISystemService interface {
	Login(request *message.UserLoginRequest) (*message.UserLoginResponse, error)
}

type SystemService struct {
	logger *zap.Logger
}

func newSystemService() *SystemService {
	return &SystemService{
		logger: initialize.Logger,
	}
}

func (s *SystemService) Login(request *message.UserLoginRequest) (*message.UserLoginResponse, error) {
	var (
		err       error
		token     string
		expiresAt int64
		config    = initialize.Config
	)

	if config.Auth.Username != request.Username || config.Auth.Password != request.Password {
		return nil, message.UserPasswdError
	}

	if token, expiresAt, err = utils.GenerateAccessToken(request.Username, 7); err != nil {
		s.logger.Error("generate access token", zap.Error(err))
		return nil, errors.New(message.Codes[message.TokenBuildError])
	}

	return &message.UserLoginResponse{
		Username:  request.Username,
		Token:     token,
		Avatar:    config.Auth.DefaultHeader,
		ExpiresAt: expiresAt,
	}, nil
}
